import { create } from 'zustand';
import { getDeviceInfo } from '../utils/model';

interface Store {
  info: any | null;
  setInfo: (obj: any) => void;

  isLooping: boolean;
  intervalId: NodeJS.Timeout | null;
  apiData: any; // 根据API返回的数据结构定义更具体的类型
  error: string | null;
  startLoop: () => void;
  stopLoop: () => void;
  isOperating: boolean;  // 添加全局操作状态
  lastOperationTime: number;  // 添加最后操作时间
  setIsOperating: (status: boolean) => void;
  updateLastOperationTime: () => void;
  delayTimer: NodeJS.Timeout | null;
  scheduleLoopStart: () => void;
}

const useStore = create<Store>((set, get) => ({
  // 设备信息
  info: {
    switch: 0, // 开关：0-待机 1-启动
    mode: 0, // 模式:  0-无 1-清洗 2-烘干 3-研磨 4-果汁 5-绵粥 6-豆浆 7-浓汤 8-辅食 9-保温
    booking: 0, // 预约 0-1440 step=10
    remainder: 0, // 剩余工作时长 0-1440 step=1
    state: 0, // 工作状态 0-待机 1-工作中 2-预约中 3-保温中
    fault: 0, // 故障 0-正常  1-3 故障
    isOnline: true// false=离线 true=在线
  },
  setInfo: info => set({ info }),

  // 处理循环
  isLooping: false,
  intervalId: null,
  apiData: null,
  error: null,
  isOperating: false,
  lastOperationTime: 0,
  setIsOperating: (status: boolean) => set({ isOperating: status }),
  updateLastOperationTime: () => set({ lastOperationTime: Date.now() }),

  startLoop: () => {
    if (get().isLooping) return; // 防止重复启动

    set({ isLooping: true });

    const fetchApi = async () => {
      try {
        getDeviceInfo();
      } catch (error: any) {
        set({ error: error });
        console.error('API Error:', error);
      }
    };

    fetchApi(); // 立即执行一次
    const id = setInterval(fetchApi, 1000); // 每5秒调用一次

    set({ intervalId: id });
  },
  // stopLoop: () => {
  //   const id = get().intervalId;
  //   if (id) {
  //     clearInterval(id);
  //     set({ intervalId: null });
  //   }
  //   set({ isLooping: false });
  // },

  // 修改原有的 stopLoop，确保清理定时器
  stopLoop: () => {
    const { intervalId, delayTimer } = get();
    if (intervalId) {
      clearInterval(intervalId);
      set({ intervalId: null });
    }
    if (delayTimer) {
      clearTimeout(delayTimer);
      set({ delayTimer: null });
    }
    set({ isLooping: false });
  },
  // 延迟启动轮询
  delayTimer: null,
  scheduleLoopStart: () => {
    const store = get();

    // 清除之前的定时器
    if (store.delayTimer) {
      clearTimeout(store.delayTimer);
    }

    // 停止当前的轮询
    store.stopLoop();

    // 设置新的定时器
    const timer = setTimeout(() => {
      store.startLoop();
      set({ delayTimer: null });
    }, 3000);

    set({ delayTimer: timer });
  },
}));

export default useStore;
